package com.yuanli.card.manage.controller;

import com.yuanli.card.manage.service.CustomerFundService;
import com.yuanli.card.manage.service.SysUserService;
import com.yuanli.card.pojo.SysUser;
import com.yuanli.card.req.CustomerFundQueryReq;
import com.yuanli.card.req.SysUserQueryReq;
import com.yuanli.card.res.FundCountAmountRes;
import com.yuanli.card.res.ResponseBean;
import com.yuanli.card.utils.JsonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by layne on 2018/11/12.
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserontroller {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private CustomerFundService customerFundService;

    //添加用户
    @PostMapping("/addUser")
    public ResponseBean addUser(SysUser sysUser) {
        sysUserService.save(sysUser);
        return ResponseBean.success();
    }

    //删除用户
    @GetMapping("/delSysUser")
    public ResponseBean delSysUser(Long id) {
        sysUserService.delSysUser(id);
        return ResponseBean.success();
    }

    @GetMapping("/query")
    public ResponseBean query(SysUserQueryReq req) {
        List<SysUser> list = sysUserService.listChild(req);
        if (list == null) {
            return ResponseBean.success();
        }
        List<Map<String, Object>> data = list.parallelStream().map(sysUser -> {
            Map<String, Object> map = JsonMapper.defaultMapper().json2Map(JsonMapper.defaultMapper().toJson(sysUser));
            CustomerFundQueryReq queryReq = new CustomerFundQueryReq();
            queryReq.setFundCustomerId(sysUser.getId().intValue());
            FundCountAmountRes amountRes = customerFundService.countAmount(queryReq);
            if (amountRes != null) {
                map.put("balance", amountRes.getRechargeAmount().subtract(amountRes.getConsumeAmount()));
            }
            return map;
        }).collect(Collectors.toList());
        return ResponseBean.success().setData(data);
    }

    @GetMapping("/listChild")
    public ResponseBean listChild(SysUserQueryReq req) {
        return ResponseBean.success().setData(sysUserService.listChild(req));
    }

    @GetMapping("/listAll")
    public ResponseBean listAll() {
        return ResponseBean.success().setData(sysUserService.listAll());
    }

    @PostMapping("/update")
    public ResponseBean update(SysUser sysUser){
        sysUserService.update(sysUser);
        return ResponseBean.success();
    }
}
